package ninesky.ContentTemp.activity;

import java.util.Random;

import ninesky.ContentTemp.R;
import ninesky.ContentTemp.R.layout;
import ninesky.ContentTemp.data.HoverPic;
import ninesky.ContentTemp.service.IMusicService;
import ninesky.ContentTemp.service.MusicService;
import ninesky.ContentTemp.util.ImageUtil;
import ninesky.ContentTemp.util.MusicUtils;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.ViewFlipper;
import android.widget.ViewSwitcher;
import android.widget.ViewSwitcher.ViewFactory;

public class MainActivity extends Activity {

	private IMusicService mService;
	private final ServiceConnection mConnection = new ServiceConnection() {

		@Override
		public void onServiceDisconnected(ComponentName name) {
			mService = null;
		}

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			mService = IMusicService.Stub.asInterface(service);
			try {
				mService.play();
				Log.d("ct", "play");
			} catch (RemoteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	};

	private ViewFlipper mFlipper;
	private ImageView mHoverImage;
	private TextView mHoverText;
	private ViewSwitcher mTitleSwitcher;
	private TextView mHoverTitle;
	private TextView mTitleSong;
	private TextView mTitleArtist;
	private TextView mIndexText;
	private Button mPlayPause;
	private TextView mPositionText;
	private TextView mDurationText;
	private SeekBar mProgress;

	private boolean paused = true;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		startService(new Intent(this, MusicService.class));
		mFlipper = (ViewFlipper) findViewById(R.id.content);
		mHoverImage = (ImageView) findViewById(R.id.hover_pic);
		mHoverText = (TextView) findViewById(R.id.hover_desc);
		mTitleSwitcher = (ViewSwitcher) findViewById(R.id.title_switcher);
		mHoverTitle = (TextView) findViewById(R.id.title_snap);
		mTitleSong = (TextView) findViewById(R.id.title_song);
		mTitleArtist = (TextView) findViewById(R.id.title_artist);
		mIndexText = (TextView) findViewById(R.id.hover_index_desc);
		mPlayPause = (Button) findViewById(R.id.btn_play_pause);
		mPositionText = (TextView) findViewById(R.id.position);
		mDurationText = (TextView) findViewById(R.id.duartion);
		mProgress = (SeekBar) findViewById(R.id.progress);

		mProgress.setMax(1000);
		
		mHoverImage.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				mFlipper.setDisplayedChild(2);
			}
		});

		mPlayPause.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (mService != null) {
					try {
						mService.playPause();
					} catch (RemoteException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		});

		mIndexText.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

			}
		});
		mTitleSwitcher.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				int displayChild = mTitleSwitcher.getDisplayedChild();
				mTitleSwitcher.setDisplayedChild(displayChild == 0 ? 1 : 0);

				displayChild = mFlipper.getDisplayedChild();
				mFlipper.setDisplayedChild(displayChild == 0 ? 1 : 0);
				new LoadHoverPicTask().execute();
			}
		});
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	public void onStop() {
		paused = true;
		mHandler.removeMessages(REFRESH);
		mService = null;
		super.onStop();
	}

	@Override
	public void onStart() {
		super.onStart();
		paused = false;

		bindService(new Intent(this, MusicService.class), mConnection,
				Service.BIND_AUTO_CREATE);

		IntentFilter f = new IntentFilter();
		f.addAction(MusicService.PLAYSTATE_CHANGED);
		f.addAction(MusicService.META_CHANGED);
		registerReceiver(mStatusListener, new IntentFilter(f));
		updateTrackInfo();
		long next = refreshNow();
		queueNextRefresh(next);
	}

	private BroadcastReceiver mStatusListener = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals(MusicService.META_CHANGED)) {
				updateTrackInfo();
				setPauseButtonImage();
				queueNextRefresh(1);
			} else if (action.equals(MusicService.PLAYSTATE_CHANGED)) {
				setPauseButtonImage();
			}
		}
	};

	private void updateTrackInfo() {
		try {
			if (mService != null) {
				String info = mService.getInfo();
				Log.d("ct", info);
				mHoverTitle.setText(info);
				mDurationText.setText(MusicUtils.makeTimeString(this, mService
						.duartion()/1000));
			}

		} catch (RemoteException e) {
			e.printStackTrace();
		}
	}

	private void setPauseButtonImage() {
		try {
			if (mService != null && mService.isPlay()) {
				mPlayPause.setText("pause");
			} else {
				mPlayPause.setText("play");
			}
		} catch (RemoteException ex) {
		}
	}

	private final Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case REFRESH:
				long next = refreshNow();
				queueNextRefresh(next);
				break;
			default:
				break;
			}
		}
	};

	private void queueNextRefresh(long delay) {
		if (!paused) {
			Message msg = mHandler.obtainMessage(REFRESH);
			mHandler.removeMessages(REFRESH);
			mHandler.sendMessageDelayed(msg, delay);
		}
	}

	private static final int REFRESH = 1;
	private long mPosOverride = -1;
	private long mDuration;

	private long refreshNow() {
		if (mService == null)
			return 500;
		try {
			long pos = mPosOverride < 0 ? mService.position() : mPosOverride;
			mDuration = mService.duartion();
			long remaining = 1000 - (pos % 1000);
			if ((pos >= 0) && (mDuration > 0)) {
				mPositionText.setText(MusicUtils.makeTimeString(this, pos / 1000));

				if (!mService.isPlay()) {
					remaining = 500;
				}
//				mDuartion.setText(MusicUtils.makeTimeString(this, mService
//						.duartion()/1000));
				mProgress.setProgress((int) (1000 * pos / mDuration));
			} else {
				mPositionText.setText("--:--");
				mProgress.setProgress(1000);
			}
			return remaining;
		} catch (RemoteException ex) {
		}
		return 500;
	}

	private class LoadHoverPicTask extends AsyncTask<Void, Void, Bitmap> {

		@Override
		protected Bitmap doInBackground(Void... params) {
			String[] imgs = {
					"http://a4.att.hudong.com/82/72/01300000026741121807723959286_s.jpg",
					"http://i1.w.hjfile.cn/doc/201005/zhangbaizhi79782.jpg" };

			Random rand = new Random();

			return ImageUtil.getWebImage(imgs[rand.nextInt(imgs.length - 1)]);
		}

		@Override
		protected void onPostExecute(Bitmap result) {
			if (result == null)
				Log.d("ct", "bitmap null");
			mHoverImage.setImageBitmap(result);
		}
	}

}